<template>
  <view class="container">
    <!-- 门店列表模式 -->
    <view v-if="showStoreList" class="store-list-container">
      <view class="page-header">
        <view class="title">选择门店</view>
        <view class="subtitle">请选择您要访问的门店</view>
      </view>
      
      <view class="search-wrapper">
        <view class="search-input">
          <view class="search-input-wrapper">
            <view class="left">
              <text class="search-icon iconfont icon-sousuo"></text>
            </view>
            <view class="right">
              <input v-model="searchValue" class="input" placeholder="请输入店铺关键字" type="text" @confirm="doSearch" />
            </view>
          </view>
        </view>
        <view class="search-button">
          <button class="button" @click="doSearch" type="warn"> 搜索 </button>
        </view>
      </view>
      
      <view class="store-list">
        <view class="store-info" v-for="(item, index) in storeList" :key="index" @click="selectStore(item)">
          <view class="store-logo">
            <image 
              class="logo-image" 
              :src="item.logo || '/static/default-avatar.png'" 
              mode="aspectFill"
            ></image>
          </view>
          <view class="base-info">
            <view class="name">{{ item.name }}</view>
            <view class="hours" v-if="item.hours">营业时间：{{ item.hours }}</view>
            <view class="address" v-if="item.address">
              <text class="location-icon iconfont icon-dingwei"></text>{{ item.address }}
            </view>
            <view class="tel" v-if="item.phone">联系电话：{{ item.phone }}</view>
          </view>
          <view class="loc-info" v-if="showDistance && item.distance">
            <text class="dis">
              <text class="distance">{{ parseFloat(item.distance).toFixed(1) }}</text>公里
            </text>
          </view>
        </view>
      </view>
      
      <empty v-if="!storeList.length && !isLoading" :isLoading="isLoading" :custom-style="{ padding: '180rpx 50rpx' }" tips="暂无店铺~">
      </empty>
    </view>

    <!-- 门店主页模式 -->
    <view v-else>
      <empty v-if="!storeInfo" :isLoading="isLoading" tips="数据加载中..."></empty>
      <block>
          <Location v-if="storeInfo" :storeInfo="storeInfo"/>
      </block>
      <block>
          <Search v-if="storeInfo" tips="请输入搜索关键字..." @event="$navTo('subpages/search/index')"/>
      </block>
      <block>
          <Banner v-if="storeInfo" :itemStyle="options.bannerStyle" :params="options.bannerParam" :dataList="banner"/>
      </block>
      <block>
          <Blank v-if="storeInfo" :itemStyle="options.blankStyle"/>
      </block>
      <block>
          <NavBar v-if="storeInfo" :itemStyle="options.navStyle" :params="{}" :dataList="options.navBar"/>
      </block>
      <block>
          <Blank v-if="storeInfo" :itemStyle="options.blankStyle"/>
      </block>
      <block>
          <Goods v-if="storeInfo" :itemStyle="options.goodsStyle" :isReflash="isReflash" ref="mescrollItem" :params="options.goodsParams"/>
      </block>
    </view>
  </view>
</template>

<script>
  import { setCartTabBadge, showMessage } from '@/utils/app'
  import Location from '@/components/page/location'
  import Search from '@/components/search'
  import Banner from '@/components/page/banner'
  import NavBar from '@/components/page/navBar'
  import Blank from '@/components/page/blank'
  import Goods from '@/components/page/goods'
  import Empty from '@/components/empty'
  import * as settingApi from '@/api/setting'
  import * as Api from '@/api/page'
  import MescrollCompMixin from "@/components/mescroll-uni/mixins/mescroll-comp.js";
  import config from '@/config'

  const App = getApp()
  
  export default {
    mixins: [MescrollCompMixin],
    components: {
       Location,
       Search,
       Banner,
       NavBar,
       Blank,
       Goods,
       Empty
    },
    data() {
      return {
        options: {
            "blankStyle": {
                "height": "5",
                "background": "#ffffff",
            },
            "navBar": [{
                        "imgUrl": "/static/nav/1.png",
                        "imgName": "icon-1.png",
                        "linkUrl": "subpages\/pay\/index",
                        "text": "买单支付",
                        "tip": "支付攒积分",
                        "color": "#666666"
                    }, {
                        "imgUrl": "/static/nav/3.png",
                        "imgName": "icon-1.png",
                        "linkUrl": "subpages\/coupon\/list?type=C",
                        "text": "领券中心",
                        "tip": "积分换好礼",
                        "color": "#666666"
                    }, {
                        "imgUrl": "/static/nav/2.png",
                        "imgName": "icon-1.png",
                        "linkUrl": "subpages\/coupon\/list?type=P",
                        "text": "预存充值",
                        "tip": "充值有优惠",
                        "color": "#666666",
                    }, {
                        "imgUrl": "/static/nav/4.png",
                        "imgName": "icon-1.png",
                        "linkUrl": "subpages\/share\/index",
                        "text": "邀请有礼",
                        "tip": "邀请获取奖励",
                        "color": "#666666"}],
            "goodsStyle": {
                "background": "#F6F6F6",
                "display": "list",
                "column": 2,
                "show": ["goodsName", "goodsPrice", "linePrice", "sellingPoint", "goodsSales"]
            },
            "goodsParams": {
                "source": "auto",
                "auto": {
                    "category": 0,
                    "goodsSort": "all",
                    "showNum": 40
                }
            },
            "bannerStyle": {
                "btnColor": "#ffffff",
                "btnShape": "round",
                "interval": 2.5,
                
            },
            "bannerParam": {
                "interval": 2000
            },
            "navStyle": {
                "background": "#ffffff",
                "rowsNum": "2",
            }
        },
        banner: [],
        storeInfo: null,
        isReflash: false,
        isLoading: false,
        // 门店列表相关
        showStoreList: false,
        storeList: [],
        searchValue: '',
        showDistance: uni.getStorageSync("latitude") ? true : false
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad({ storeId }) {
      storeId = storeId ? parseInt(storeId) : 0;
      if (storeId > 0) {
          uni.setStorageSync('storeId', storeId);
          uni.setStorageSync("reflashHomeData", true);
          this.showStoreList = false;
      } else {
          // 首先获取门店列表，判断是否需要显示门店选择页面
          this.initStoreList();
      }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      const app = this;
      showMessage();
      setCartTabBadge();
      app.onGetStoreInfo();
      uni.getLocation({
          type: 'gcj02',
          success(res){
              uni.setStorageSync('latitude', res.latitude);
              uni.setStorageSync('longitude', res.longitude);
              app.onGetStoreInfo();
          },
          fail(e) {
             // empty
          }
      })
    },

    methods: {
        
        /**
         * 加载页面数据
         * @param {Object} callback
         */
        getPageData(callback) {
          const app = this;
          Api.home()
            .then(result => {
                 app.banner = result.data.banner;
                 uni.removeStorageSync("reflashHomeData");
                 app.isReflash = false;
            })
            .finally(() => callback && callback())
        },
        
        /**
         * 下拉刷新
         */
        onPullDownRefresh() {
          // 获取数据
          this.getPageData(() => {
             uni.stopPullDownRefresh()
          })
        },
        
        /**
         * 初始化门店列表
         */
        initStoreList() {
          const app = this;
          app.isLoading = true;
          settingApi.storeList('')
            .then(result => {
              app.storeList = result.data.data || [];
              app.isLoading = false;
              
              if (app.storeList.length === 0) {
                // 没有门店，显示空状态
                app.showStoreList = true;
              } else if (app.storeList.length === 1) {
                // 只有一个门店，直接进入门店主页
                app.selectStore(app.storeList[0]);
              } else {
                // 多个门店，显示门店列表
                app.showStoreList = true;
              }
            })
            .catch(() => {
              app.isLoading = false;
              app.showStoreList = true;
            });
        },

        /**
         * 获取门店列表
         */
        getStoreList() {
          const app = this;
          app.isLoading = true;
          settingApi.storeList(app.searchValue)
            .then(result => {
              app.storeList = result.data.data || [];
              app.isLoading = false;
            })
            .catch(() => {
              app.isLoading = false;
            });
        },

        /**
         * 搜索门店
         */
        doSearch() {
          this.getStoreList();
        },

        /**
         * 选择门店
         */
        selectStore(store) {
          const app = this;
          // 设置选中的门店
          uni.setStorageSync("storeId", store.id);
          uni.setStorageSync("merchantNo", store.merchantNo);
          uni.setStorageSync("reflashHomeData", true);
          
          // 切换到门店主页模式
          app.showStoreList = false;
          app.storeInfo = store;
          
          // 加载门店主页数据
          app.getPageData();
        },

        /**
         * 获取默认店铺
         * */
         onGetStoreInfo() {
            const app = this;
            // 如果正在显示门店列表，不执行此方法
            if (app.showStoreList) {
              return;
            }
            
            settingApi.systemConfig()
             .then(result => {
                 app.storeInfo = result.data.storeInfo;
                 if (app.storeInfo) {
                     uni.setStorageSync("storeId", app.storeInfo.id);
                     uni.setStorageSync("merchantNo", app.storeInfo.merchantNo);
                     // 判断是否需要更新页面
                     let isReflash = uni.getStorageSync("reflashHomeData");
                     app.isReflash = isReflash;
                     if (isReflash === true) {
                         app.getPageData();
                     }
                 }
             })
         }
    },

    /**
     * 分享当前页面
     */
    onShareAppMessage() {
      const app = this
      return {
         title: config.name,
         path: "/pages/index/index?" + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      const { page } = app
      return {
        title: config.name,
        path: "/pages/index/index?" + app.$getShareUrlParams()
      }
    }

  }
</script>

<style lang="scss" scoped>
  .container {
    background: #f7f7f7;
    min-height: 100vh;
  }

  // 门店列表样式
  .store-list-container {
    padding: 20rpx;
  }

  .page-header {
    text-align: center;
    padding: 60rpx 0 40rpx;
    background: #fff;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .subtitle {
      font-size: 28rpx;
      color: #666;
    }
  }

  .search-wrapper {
    display: flex;
    height: 78rpx;
    margin-bottom: 20rpx;
  }

  // 搜索输入框
  .search-input {
    width: 80%;
    background: #fff;
    border-radius: 50rpx 0 0 50rpx;
    box-sizing: border-box;
    overflow: hidden;
    border: solid 1px #cccccc;
    
    .search-input-wrapper {
      display: flex;
      
      .left {
        display: flex;
        width: 60rpx;
        justify-content: center;
        align-items: center;
        
        .search-icon {
          display: block;
          color: #666666;
          font-size: 30rpx;
          font-weight: bold;
        }
      }

      .right {
        flex: 1;

        input {
          font-size: 28rpx;
          height: 78rpx;
          line-height: 78rpx;
          
          .input-placeholder {
            color: #aba9a9;
          }
        }
      }
    }
  }

  // 搜索按钮
  .search-button {
    width: 20%;
    box-sizing: border-box;

    .button {
      line-height: 78rpx;
      height: 78rpx;
      font-size: 28rpx;
      border-radius: 0 20px 20px 0;
      background: $fuint-theme;
    }
  }

  // 店铺列表
  .store-list {
    .store-info {
      display: flex;
      align-items: center;
      overflow: hidden;
      border: 2rpx solid #cccccc;
      min-height: 160rpx;
      border-radius: 16rpx;
      margin-top: 10rpx;
      margin-bottom: 10rpx;
      padding: 30rpx;
      background: #FFFFFF;
      transition: all 0.3s ease;
      
      &:active {
        background: #f5f5f5;
        transform: scale(0.98);
      }
      
      .store-logo {
        width: 120rpx;
        height: 120rpx;
        margin-right: 20rpx;
        flex-shrink: 0;
        
        .logo-image {
          width: 100%;
          height: 100%;
          border-radius: 12rpx;
          border: 2rpx solid #e0e0e0;
          background: #f5f5f5;
        }
      }
      
      .base-info {
        flex: 1;
        min-width: 0; // 防止文字溢出
        
        .name {
          font-size: 32rpx;
          font-weight: bold;
          margin-bottom: 8rpx;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .hours, .tel {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 6rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .address {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 6rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .location-icon {
          color: #f03c3c;
          font-weight: bold;
          margin-right: 5rpx;
        }
      }
      
      .loc-info {
        color: #666666;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100rpx;
        flex-shrink: 0;
        
        .dis {
          font-size: 22rpx;
          text-align: center;
        }
        
        .distance {
          font-weight: bold;
          color: #f03c3c;
          font-size: 24rpx;
        }
      }
    }
  }
</style>
